<?php

namespace app\common\reptile;

use app\admin\model\Article;
use app\admin\model\Company;
use app\admin\model\Job;
use app\admin\model\Labels;
use app\common\library\HttpCurl;
use app\common\model\Area;
use fast\Http;

/**
 * create by PhpStorm 2025/8/3 18:28
 * szyc.com app\common\reptile@www_iguopin_com
 * 行止之行 <xingzhi8711@gmail.com>
 * 国聘网-数据抓取任务
 */
class www_iguopin_com
{
    private $method="www_iguopin_com";
    public  $headers = [
        "accept: application/json, text/plain, */*",
        "accept-language: zh-CN,zh;q=0.9",
        "content-type: application/json",
        "device: pc",
//        "origin: ".$websiteList["web_url"],
        "priority: u=1, i",
//        "referer: ".$websiteList["web_url"]."/",
        "sec-ch-ua: \"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
        "sec-ch-ua-mobile: ?0",
        "sec-ch-ua-platform: \"Windows\"",
        "sec-fetch-dest: empty",
        "sec-fetch-mode: cors",
        "sec-fetch-site: same-site",
        "subsite: iguopin",
        "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
    ];
    public $config;
    private $cateStr="";
    private $cateMap=[];
    public function __construct()
    {
        $websiteList=config("websitepath.".$this->method);
        $this->config=$websiteList;
        $this->headers[]="origin: ".$websiteList["web_url"];
        $this->headers[]="referer: ".$websiteList["web_url"]."/";
    }
    /*抓取并保存职位信息*/
    public function init()
    {
        $websiteList=$this->config;
        foreach ($websiteList['path_list'] as $key => $value) {
            for ($i=1;$i<=$value['total_page'];$i++){
                $data=$this->www_iguopin_com_curl($websiteList,$value);
                if(!$data){
                    continue;
                }
                $lists=$data['data']['list'];
                foreach ($lists as $list) {
//                    if(Job::get(['uniquid'=>$list['job_id']])) continue;
                    if($list['update_time']<$websiteList['lose_time']) break;
                    try {
                        $companyName=$list['company_name'];
                        $company=Company::get(['name'=>$companyName]);
                        if(!$company){
                            $this->initCompany($list['company_id']);
                            $company=Company::get(['name'=>$companyName]);
                        }
                        $insertData=[
                            'title'=>$list['job_name'],
                            'companey_name'=>$list['company_name'],
                            'child_companey_name'=>$list['department_cn'],
                            'category_name'=>$list['category_cn'],
                            'work_localtion'=>isset($list['district_list'][0]['area_cn'])?$list['district_list'][0]['area_cn']:'',
                            'add_time'=>$list['start_time'],
                            'job_respon'=>$list['contents'],
                            'from_url'=>"https://www.iguopin.com/job/detail?id=".$list['job_id'],
                            'web_url'=>"https://www.iguopin.com",
                            'web_title'=>$websiteList['web_title'],
                            'uniquid'=>$list['job_id'],
                            'education'=>$list['education_cn'],
                            'company_scale'=>isset($list['company_info']['scale_cn'])?$list['company_info']['scale_cn']:'',
                            'company_nature'=>isset($list['company_info']['nature_cn'])?$list['company_info']['nature_cn']:'',
                            'financing_stage'=>isset($list['company_info']['financing_stage_cn'])?$list['company_info']['financing_stage_cn']:'',
                            'industry'=>isset($list['company_info']['industry_cn'])?$list['company_info']['industry_cn']:'',
                            'job_cate'=>$list['category_cn'],
                            'nature'=>$list['nature_cn'],
                            'experience'=>$list['experience_cn'],
                            'company_id'=>$company->id,
                            'source'=>"国聘网"
                        ];
                        $list=Job::get(['uniquid'=>$list['job_id']]);
                        if(!$list){
                            $list=Job::create($insertData);
                        }else{
                            $list->save($insertData);
                        }
                    }catch (\Exception $e){
                        setLog(__METHOD__,"错误:".$e->getLine());
                        setLog(__METHOD__,$e->getMessage());
                        continue;
                    }
//                    Job::create($insertData);
                }
            }
        }
        return true;
    }
    public function initCompany($companyId)
    {
        $url="https://gp-api.iguopin.com/api/company/index/v1/home?company_id=".$companyId;
        $headers=$this->headers;
        $res=$this->initArticle($url,$headers);
        $companyInfo=$res['data']['company_info'];
        $companey=Company::get(['name'=>$companyInfo['name']]);
        if(!$companey){
            $companey=company::create([
                'name'=>$companyInfo['name'],
                'logo'=>$companyInfo['show_logo'],
                'info'=>$companyInfo['introduction'],
                'pname'=>$companyInfo['group_id']==$companyInfo['id']?0:$companyInfo['group_id'],
                'link'=>$companyInfo['website'],
                'pid'=>0
            ]);
        }
        Company::where('pname',$companyId)->update(['pid'=>$companey['id'],'pname'=>$companey['name']]);
        if($companyInfo['id']==$companyInfo['group_id']){
            $companey->pid=0;
            $companey->pname="";
            $companey->save();
        }else{
            $this->initCompany($companyInfo['group_id']);
        }

    }
    /*抓取并保存内容信息*/
    public function article()
    {
        $header=$this->headers;
        for($i=1;$i<=20;$i++){
            $url="https://gp-api.iguopin.com/api/activity/jobfair/v1/list";
            $result=$this->initArticle($url,$header,['page'=>$i,"page_size"=>20]);
            if(isset($result["data"]['list'])){
                $lists=$result['data']['list'];
                foreach ($lists as $list) {
                    $insertData=[
                        'title'=>$list['title'],
                        'content'=>"",
                        'link'=>$list['link'],
                        'createtime'=>time(),
                        'image'=>$list['show_cover_img'],
                        'category_id'=>17,
                    ];
                    $uniquid=md5(json_encode($insertData));
                    $list=Article::where('uniquid',$uniquid)->find();
                    if($list){
                        continue;
                    }
                    $insertData['uniquid']=$uniquid;
                    Article::create($insertData);
                }
            }
        }
    }
    public function setCate()
    {
        $cateList=config('cate');
        foreach ($cateList as $key=>$cate) {
            $this->initCate($cate,$key,0);
        }
    }
    private function initCateStr($data,$cateStr)
    {
        if($data['children']){
            foreach ($data['children'] as $key => $value) {
                $cateStr=$cateStr?$cateStr."-".$data['label']:$data['label'];;
                $cateStr.="-".$value['label'];
                $this->initCateStr($value,$cateStr);
                $cateStr="";
            }
        }else{
            $cateStr=$cateStr?$cateStr:$data['label'];
            $this->cateMap[$data['label']]=$cateStr;

        }
        return false;
    }
    public function getCate()
    {
        $jsonPath=APP_PATH."json/cate.json";
        $json=file_get_contents($jsonPath);
        $data=json_decode($json,true);
        $cateData=[];
        $keyMap=[
            'company_nature'=>"company_nature",
            'company_scale'=>"company_scale",
            'financing_stage'=>"financing_stage",
            'job_education'=>"education",
            'job_experience'=>"experience",
            'job_major'=>"major_require",
            'job_nature'=>"nature",
            'research'=>"industry",
            'zwfl'=>"job_cate",
        ];
        foreach ($data as $key => $value) {
            $cateKey=$keyMap[$key];
            $cateData[$cateKey]=$this->initCate($value);
        }
        file_put_contents(
            APP_PATH."extra/cate.php",
            '<?php' . "\n\nreturn " . var_export_short($cateData) . ";\n"
        );
    }
    public function area()
    {
        $areaTree=config('area');
        $this->initArea($areaTree);

    }
    private function initArea($areaTree,$parentId="")
    {
        foreach ($areaTree as $key => $value) {
            $value['code']=$value['value'];
            $children=$value['children'];
            unset($value['value']);
            unset($value['is_repeat']);
            unset($value['is_special']);
            unset($value['children']);
            $value['parent_code']=$parentId;
            $area=Area::get(['code'=>$value['code']]);
            if(!$area){
                Area::create($value);
            }
            if($children){
                $this->initArea($children,$value['code']);
            }
        }
    }
    private function initCate($value,$key,$parentId=0,$parentLabel="")
    {
        foreach ($value as $k => $v) {
            $data['label']=$v['label'];
            $data['parent_id']=$parentId;
            $data['type']=$key;
            $data['parent_label']=$parentLabel;
            $label=Labels::create($data);
            if($v['children']){
                $this->initCate($v['children'],$key,$label->id,$v['label']);
            }
        }
    }
    private function www_iguopin_com_curl($websiteList,$pathList)
    {
        $url = $pathList['value'];
        $headers = $this->headers;
        $data = [
            "search" => [
                "page" => 1,
                "page_size" => 200,
            ],
            "recom" => [
                "update_time" => true,
                "company_nature" => true,
                "hot_job" => true
            ]
        ];
        $ch = curl_init($url);

        // 设置cURL选项
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        // 执行请求
        $response = curl_exec($ch);

        // 检查错误
        if (curl_errno($ch)) {
            setLog(__METHOD__,"cURL error :".curl_error($ch));
            curl_close($ch);
            return false;
//            echo 'cURL Error: ' . curl_error($ch);
        } else {
            // 输出响应
            $responseData = json_decode($response, true);
            return $responseData;

        }

        // 关闭cURL资源

    }
    public function initArticle($url,$headers,$data=[])
    {
        $ch = curl_init($url);

        // 设置cURL选项
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        // 执行请求
        $response = curl_exec($ch);

        // 检查错误
        if (curl_errno($ch)) {
            setLog(__METHOD__,"cURL error :".curl_error($ch));
            curl_close($ch);
            return false;
//            echo 'cURL Error: ' . curl_error($ch);
        } else {
            // 输出响应
            $responseData = json_decode($response, true);
            return $responseData;

        }
    }
}